﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using DBUtility;
using Common;
using System.Collections.Generic;
namespace DeliveryManage.DAL
{
	/// <summary>
	/// 数据访问类:Pro_Orders
	/// </summary>
	public partial class Pro_Orders
	{
		public Pro_Orders()
		{}
		#region  BasicMethod

		/// <summary>
		/// 得到最大ID
		/// </summary>
		public int GetMaxId()
		{
		return DbHelperSQL.GetMaxID("Id", "Pro_Orders"); 
		}

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(int Id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from Pro_Orders");
			strSql.Append(" where Id=@Id");
			SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
			parameters[0].Value = Id;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public int Add(DeliveryManage.Model.Pro_Orders model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into Pro_Orders(");
			strSql.Append("OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created)");
			strSql.Append(" values (");
			strSql.Append("@OrderNo,@DeliveryWay,@EmployeeId,@OrderType,@Status,@CustomerName,@CustomerTel,@CustomerAddress,@CustomerSex,@TotalAmount,@Remark,@Created)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@OrderNo", SqlDbType.NVarChar,20),
					new SqlParameter("@DeliveryWay", SqlDbType.Int,4),
					new SqlParameter("@EmployeeId", SqlDbType.Int,4),
					new SqlParameter("@OrderType", SqlDbType.Bit,1),
					new SqlParameter("@Status", SqlDbType.Int,4),
					new SqlParameter("@CustomerName", SqlDbType.NVarChar,30),
					new SqlParameter("@CustomerTel", SqlDbType.NVarChar,11),
					new SqlParameter("@CustomerAddress", SqlDbType.NVarChar,128),
					new SqlParameter("@CustomerSex", SqlDbType.Bit,1),
					new SqlParameter("@TotalAmount", SqlDbType.Decimal,9),
					new SqlParameter("@Remark", SqlDbType.NVarChar,200),
					new SqlParameter("@Created", SqlDbType.DateTime)};
			parameters[0].Value = model.OrderNo;
			parameters[1].Value = model.DeliveryWay;
			parameters[2].Value = model.EmployeeId;
			parameters[3].Value = model.OrderType;
			parameters[4].Value = model.Status;
			parameters[5].Value = model.CustomerName;
			parameters[6].Value = model.CustomerTel;
			parameters[7].Value = model.CustomerAddress;
			parameters[8].Value = model.CustomerSex;
			parameters[9].Value = model.TotalAmount;
			parameters[10].Value = model.Remark;
			parameters[11].Value = model.Created;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(DeliveryManage.Model.Pro_Orders model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update Pro_Orders set ");
			strSql.Append("OrderNo=@OrderNo,");
			strSql.Append("DeliveryWay=@DeliveryWay,");
			strSql.Append("EmployeeId=@EmployeeId,");
			strSql.Append("OrderType=@OrderType,");
			strSql.Append("Status=@Status,");
			strSql.Append("CustomerName=@CustomerName,");
			strSql.Append("CustomerTel=@CustomerTel,");
			strSql.Append("CustomerAddress=@CustomerAddress,");
			strSql.Append("CustomerSex=@CustomerSex,");
			strSql.Append("TotalAmount=@TotalAmount,");
			strSql.Append("Remark=@Remark,");
			strSql.Append("Created=@Created");
			strSql.Append(" where Id=@Id");
			SqlParameter[] parameters = {
					new SqlParameter("@OrderNo", SqlDbType.NVarChar,20),
					new SqlParameter("@DeliveryWay", SqlDbType.Int,4),
					new SqlParameter("@EmployeeId", SqlDbType.Int,4),
					new SqlParameter("@OrderType", SqlDbType.Bit,1),
					new SqlParameter("@Status", SqlDbType.Int,4),
					new SqlParameter("@CustomerName", SqlDbType.NVarChar,30),
					new SqlParameter("@CustomerTel", SqlDbType.NVarChar,11),
					new SqlParameter("@CustomerAddress", SqlDbType.NVarChar,128),
					new SqlParameter("@CustomerSex", SqlDbType.Bit,1),
					new SqlParameter("@TotalAmount", SqlDbType.Decimal,9),
					new SqlParameter("@Remark", SqlDbType.NVarChar,200),
					new SqlParameter("@Created", SqlDbType.DateTime),
					new SqlParameter("@Id", SqlDbType.Int,4)};
			parameters[0].Value = model.OrderNo;
			parameters[1].Value = model.DeliveryWay;
			parameters[2].Value = model.EmployeeId;
			parameters[3].Value = model.OrderType;
			parameters[4].Value = model.Status;
			parameters[5].Value = model.CustomerName;
			parameters[6].Value = model.CustomerTel;
			parameters[7].Value = model.CustomerAddress;
			parameters[8].Value = model.CustomerSex;
			parameters[9].Value = model.TotalAmount;
			parameters[10].Value = model.Remark;
			parameters[11].Value = model.Created;
			parameters[12].Value = model.Id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int Id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Pro_Orders ");
			strSql.Append(" where Id=@Id");
			SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
			parameters[0].Value = Id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string Idlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Pro_Orders ");
			strSql.Append(" where Id in ("+Idlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public DeliveryManage.Model.Pro_Orders GetModel(int Id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 Id,OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created from Pro_Orders ");
			strSql.Append(" where Id=@Id");
			SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
			parameters[0].Value = Id;

			DeliveryManage.Model.Pro_Orders model=new DeliveryManage.Model.Pro_Orders();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public DeliveryManage.Model.Pro_Orders DataRowToModel(DataRow row)
		{
			DeliveryManage.Model.Pro_Orders model=new DeliveryManage.Model.Pro_Orders();
			if (row != null)
			{
				if(row["Id"]!=null && row["Id"].ToString()!="")
				{
					model.Id=int.Parse(row["Id"].ToString());
				}
				if(row["OrderNo"]!=null)
				{
					model.OrderNo=row["OrderNo"].ToString();
				}
				if(row["DeliveryWay"]!=null && row["DeliveryWay"].ToString()!="")
				{
					model.DeliveryWay=int.Parse(row["DeliveryWay"].ToString());
				}
				if(row["EmployeeId"]!=null && row["EmployeeId"].ToString()!="")
				{
					model.EmployeeId=int.Parse(row["EmployeeId"].ToString());
				}
				if(row["OrderType"] !=null && row["OrderType"].ToString()!="")
				{
                    if ((row["OrderType"].ToString() == "1") || (row["OrderType"].ToString().ToLower() == "true"))
                    {
                        model.OrderType = true;
                    }
                    else
                    {
                        model.OrderType = false;
                    }
				}
				if(row["Status"]!=null && row["Status"].ToString()!="")
				{
					model.Status=int.Parse(row["Status"].ToString());
				}
				if(row["CustomerName"]!=null)
				{
					model.CustomerName=row["CustomerName"].ToString();
				}
				if(row["CustomerTel"]!=null)
				{
					model.CustomerTel=row["CustomerTel"].ToString();
				}
				if(row["CustomerAddress"]!=null)
				{
					model.CustomerAddress=row["CustomerAddress"].ToString();
				}
				if(row["CustomerSex"]!=null && row["CustomerSex"].ToString()!="")
				{
					if((row["CustomerSex"].ToString()=="1")||(row["CustomerSex"].ToString().ToLower()=="true"))
					{
						model.CustomerSex=true;
					}
					else
					{
						model.CustomerSex=false;
					}
				}
				if(row["TotalAmount"]!=null && row["TotalAmount"].ToString()!="")
				{
					model.TotalAmount=decimal.Parse(row["TotalAmount"].ToString());
				}
				if(row["Remark"]!=null)
				{
					model.Remark=row["Remark"].ToString();
				}
				if(row["Created"]!=null && row["Created"].ToString()!="")
				{
					model.Created=DateTime.Parse(row["Created"].ToString());
				}

                //获取商品信息
                model.OrderGoods = GetOrderGoodsList(model.Id);
            }
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select Id,OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created ");
			strSql.Append(" FROM Pro_Orders ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" Id,OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created ");
			strSql.Append(" FROM Pro_Orders ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM Pro_Orders ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.Id desc");
			}
			strSql.Append(")AS Row, T.*  from Pro_Orders T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

        /*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "Pro_Orders";
			parameters[1].Value = "Id";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

        #endregion  BasicMethod
        #region  ExtensionMethod
        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public List<DeliveryManage.Model.Pro_Orders> GetQueryList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from (");
            strSql.Append("select * FROM Pro_Orders");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(") dual");
            recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
            DataSet ds = DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
            if (ds != null && ds.Tables[0] != null)
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    list.Add(DataRowToModel(item));
                }
            }
            return list;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public DeliveryManage.Model.Pro_Orders GetModelDetail(int OrderId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 Id,OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created from Pro_Orders ");
            strSql.Append(" where Id=@Id");
            SqlParameter[] parameters = {
                    new SqlParameter("@Id", SqlDbType.Int,4)
            };
            parameters[0].Value = OrderId;

            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                model = DataRowToModel(ds.Tables[0].Rows[0]);
				//获取商品信息
				model.OrderGoods = GetOrderGoodsList(OrderId);
                return model;
            }
            else
            {
                return model;
            }
        }

        /// <summary>
        /// 获取订单所有商品
        /// </summary>
        public List<DeliveryManage.Model.Pro_OrderGoods> GetOrderGoodsList(int OrderId)
        {
            List<DeliveryManage.Model.Pro_OrderGoods> list = new List<DeliveryManage.Model.Pro_OrderGoods>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * FROM Pro_OrderGoods");
            if (OrderId > 0)
            {
				strSql.Append(" where OrderId =" + OrderId);
            }
            
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            if (ds != null && ds.Tables[0] != null)
            {
                DeliveryManage.DAL.Pro_OrderGoods ogdal = new Pro_OrderGoods();
                DeliveryManage.DAL.Pro_ShopGoods sgdal = new Pro_ShopGoods();
                foreach (DataRow item in ds.Tables[0].Rows)
                {
					var model = ogdal.DataRowToModel(item);
					var sgdmodel= sgdal.GetModel(int.Parse(item["GoodsId"].ToString()));
					if (sgdmodel != null) 
					{
						model.Stock = sgdmodel.Stock;
						model.NormalPrice = sgdmodel.NormalPrice;
                        model.CostPrice = sgdmodel.CostPrice;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取所有订单数据
        /// </summary>
        public List<DeliveryManage.Model.Pro_Orders> GetAllOrderList(string sqlWhere)
        {
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * FROM Pro_Orders");
            if (!string.IsNullOrEmpty(sqlWhere))
            {
                strSql.Append(" where " + sqlWhere);
            }

            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            if (ds != null && ds.Tables[0] != null)
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    list.Add(DataRowToModel(item));
                }
            }
            return list;
        }

        /// <summary>
        /// 获取指定数量订单数据
        /// </summary>
        public List<DeliveryManage.Model.Pro_Orders> GetTopOrderList(int Top, string strWhere, string filedOrder)
        {
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" Id,OrderNo,DeliveryWay,EmployeeId,OrderType,Status,CustomerName,CustomerTel,CustomerAddress,CustomerSex,TotalAmount,Remark,Created ");
            strSql.Append(" FROM Pro_Orders ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            if (ds != null && ds.Tables[0] != null)
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    list.Add(DataRowToModel(item));
                }
            }
            return list;
        }
        #endregion  ExtensionMethod
    }
}

